package freespiritsocial.io.user.viewmodel

import androidx.lifecycle.MutableLiveData
import freespiritsocial.io.user.R
import freespiritsocial.io.user.data.model.bean.ApiRefreshResult
import freespiritsocial.io.user.data.model.bean.PostPojo
import freespiritsocial.io.user.data.model.bean.UserInfo
import freespiritsocial.io.user.network.apiService
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.viewmodel.delegates.IPeopleApi
import freespiritsocial.io.user.viewmodel.delegates.PeopleDelegate
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.ext.request

/**
 * @description
 * @author csw
 * @date 2021-10-17
 */
class MineViewModel: BaseViewModel(),IPeopleApi by PeopleDelegate() {
    companion object {
        val userTab = arrayOf(appContext.getString(R.string.posted),appContext.getString(R.string.tagged),"Saved")
        val peopleTab = arrayOf(appContext.getString(R.string.posted),appContext.getString(R.string.tagged))
    }

    val changeViewHeightEvent = MutableLiveData<Int>()

    //是否是本人
    val isUser = BooleanObservableField(false)
    val tab: Array<String>
        get() {
            return if (isUser.get()) userTab else peopleTab
        }
    val user = MutableLiveData<UserInfo>()
    fun getList(queryType: Int,refresh: Boolean = false,boundaryValue: Long? = null,success: (ApiRefreshResult<PostPojo>) -> Unit) {
        request({
            apiService.getUserPostList(queryType,boundaryValue,if (isUser.get()) null else user.value?.userId)
        },{
            success(ApiRefreshResult(refresh,it?.list ?: arrayListOf(),true))
        })
    }

    fun getPost(id: Long?,action: (PostPojo) -> Unit) {
        request({
            apiService.getInvitationDetail(id)
        },{
            action(it)
        },isShowDialog = true)
    }

    fun publishPost(postPojo: PostPojo,callback: () -> Unit) {
        request({
            if (postPojo.isEdit)
                apiService.updateInvitation(postPojo)
            else
                apiService.publishPost(postPojo)
        },{
            callback()
        })
    }

    fun getUserInfo() {
        request({
            apiService.getUserInfo(if (isUser.get()) null else user.value?.userId)
        },{
            if (isUser.get())
                CacheUtil.refreshUserInfo(it)
            else
                user.postValue(it)
        })
    }
}